/*
 * User: rant
 * Date: 20/12/2006
 *
 *
 */
package laMalinche.rete.nodes.tailing;

import laMalinche.rete.nodes.BasicConditionNode;
import laMalinche.rete.nodes.StopEvaluatingException;
import laMalinche.rete.rule.ActObservable;
import laMalinche.rete.rule.ConditionObservable;
import laMalinche.DevMode;

import static java.lang.Boolean.FALSE;

/**
 Node tailing its condition
 */
public class BasicTailingsConditionNode<T extends ConditionObservable> extends BasicConditionNode<T> implements
		ActObservableHolder {

    public BasicTailingsConditionNode() {
               DevMode.getInstance().getInjector().injectMembers(this);
    }

    public void initialize() {
        final ActObservable actObservable = getActObservable();
		TailingManager basicTailingManager = actObservable.getTailingManager();
		getWorkingMemory().setConditionNode(this);
		basicTailingManager.addPropertyTouchedListener(getWorkingMemory());
	}

	public void update() {
        if (!FALSE.equals(isConditionMet()) && !isRelevant()) {
			setConditionMet(null);
			return;
		}
        Boolean complied;
        try {
			complied = isConditionComplied();
		} catch (StopEvaluatingException e) {
			complied = null;
		}
		setConditionMet(complied);
	}

	@Override
	public void detach() {
		if (getWorkingMemory() != null) {
			getWorkingMemory().detach();
		}
		super.detach();
	}

	



	public void stopRuleExecution() {
		throw new StopEvaluatingException();
	}

	public ActObservable getActObservable() {
		return getCondition();
	}
}